﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
//using System.Web.Script.Serialization;


namespace MeetingFinder
{
    public partial class MainPage : PhoneApplicationPage
    {
        private List<String> _confirmedMeetingList = new List<string>();
        private List<String> _updatedMeetingList = new List<string>();
        private List<String> _pendingMeetingList = new List<string>();
        private string userID = null;

        // Constructor
        public MainPage()
        {
            

            ApplicationBar = new ApplicationBar();

            InitializeApplicationBar();

            AddButtonToAppBar("/Assets/Images/add.png", "New Meeting", CreateMeetingButton_Click);

            AddButtonToAppBar("/Assets/Images/check.png", "Login To IVLE", LoginToIVLEButton_Click);

            //SetUserID(null);

            //userID = GetUserID();
            //if (userID == "UserID.txt does not exist" || userID == "") 
            //    LandingPage.Title = "Please Login to IVLE";
            //else
            //    LandingPage.Title = userID;

            //InitializeLocaLists();


            WebClient proxy = new WebClient();
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {

                    //string jsonString = "{\"listArray\":\"HI\", \"listArray2\":[ [2, 1], [2, 1], [2, 1], [4, 1], [5, 1], [6, 1] ]}";

                        //List<int> listArray = new List<int>();

                        //using (MemoryStream jsonStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
                        //{
                        //    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<int>)); 
                    //List<int> array = serializer.ReadObject(jsonStream) as List<int>;

                        //    listArray = array;

                        //}

                    string result = e.Result;
                    var jList = JsonConvert.DeserializeObject<List<NewMeetingItem>>(result);


                    //using (MemoryStream jsonStream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
                    //{
                    //    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(String));
                    //   String array = serializer.ReadObject(jsonStream) as String;


                    //}

                        
                }

            };
            proxy.DownloadStringAsync(new Uri("http://54.251.58.144/meeting/user/completed/7", UriKind.Absolute));

            InitializeComponent();
            
        }


//Private / Helper Methods----------------------------------------------------------------------------------

        //creates new instance of Application bar
        private void InitializeApplicationBar()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
        }

        //crates a new button on application bar
        //sets icon image
        //set click even handler
        private void AddButtonToAppBar(String IconPath, String DescriptionText, EventHandler ClickEventHandler)
        {
            ApplicationBarIconButton CreateNewMeetingButton = new ApplicationBarIconButton();
            CreateNewMeetingButton.IconUri = new Uri(IconPath, UriKind.Relative);
            CreateNewMeetingButton.Text = DescriptionText;
            ApplicationBar.Buttons.Add(CreateNewMeetingButton);
            CreateNewMeetingButton.Click += new EventHandler(ClickEventHandler);
        }

        //test function to set userID
        private void SetUserID(string userID)
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            //create new file
            using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("UserID.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
            {
                string someTextData = userID;
                writeFile.WriteLine(someTextData);
                writeFile.Close();
            }
        }

        //reads userID from text file in isolated storage
        private string GetUserID()
        {
            string userID;
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("UserID.txt", FileMode.Open, FileAccess.Read);

                using (StreamReader reader = new StreamReader(fileStream))
                {    //Visualize the text data in a TextBlock text
                    userID = reader.ReadLine();
                }
            }
            catch (IsolatedStorageException ex)
            {
                userID = "UserID.txt does not exist";
            }
            return userID;
        }

        //Sends request to server and initializes local Lists 
        private void InitializeLocaLists()
        {
            // for now just create test list with private helper methods

            //initializing meeting list for Main Page Pivot
            var received = App.Current as App;
                received._meetingItemList = CreateTestList();

            var meetingByStatus = from meeting in received._meetingItemList
                                    group meeting by meeting._meetingStatus into m
                                    orderby m.Key
                                    select new Group<MeetingItem>(m.Key.ToString(), m);
            this.meetingList.ItemsSource = meetingByStatus; 

            //initialize project group list
            received._projectGroupList = CreateProjectGroupTestList();

            //initialize History List
            received._historyItemList = CreateHistoryTestList();

            var historyByGroup = from historyItem in received._historyItemList
                                 group historyItem by historyItem._historyProjectGroup into h
                                  orderby h.Key
                                  select new Group<HistoryItem>(h.Key.ToString(), h);
            this.historyList.ItemsSource = historyByGroup; 

            //initizlize Notification list
            received._notificationItemList = CreateNotificationsTestList();

            var notificationByDate = from notificationItem in received._notificationItemList
                                     group notificationItem by notificationItem._notificationDate.Date into n
                                 orderby n.Key
                                 select new Group<NotificationItem>(n.Key.ToShortDateString(), n);
            this.notificationList.ItemsSource = notificationByDate; 

        }


        //just creates a list for testing
        private List<MeetingItem> CreateTestList()
        {
            List<MeetingItem> testList = new List<MeetingItem>();
            for (int i = 0; i < 5; i++)
            {
                MeetingItem meetingItem = new MeetingItem( ("Project" + i),DateTime.Now,("Bench" + i),("Agenda" + i),(MeetingItem.Status.Completed) );
                testList.Add(meetingItem);
            }

            for (int i = 0; i < 5; i++)
            {
                MeetingItem meetingItem = new MeetingItem(("Project" + i),DateTime.Now,("Bench" + i),("Agenda" + i),(MeetingItem.Status.Pending));
                testList.Add(meetingItem);
            }

            for (int i = 0; i < 5; i++)
            {
                MeetingItem meetingItem = new MeetingItem(("Project" + i),DateTime.Now,("Bench" + i),("Agenda" + i),(MeetingItem.Status.Updated));
                testList.Add(meetingItem);
            }
            return testList;
        }

        //just creates a list for testing, get actual list from a main store, may be dict
        private List<ProjectGroup> CreateProjectGroupTestList()
        {
            List<ProjectGroup> testList = new List<ProjectGroup>();

            for (int i = 0; i < 5; i++)
            {
                ProjectGroup group = new ProjectGroup();
                group._groupName = "Group " + i;
                group._moduleName = "Module " + i + i;

                testList.Add(group);
            }
            return testList;
        }


        private List<HistoryItem> CreateHistoryTestList()
        {
            List<HistoryItem> testList = new List<HistoryItem>();

            for (int i = 0; i < 5; i++)
            {
                
                for (int j = 0; j < 3; j++)
                {
                    DateTime date = DateTime.Now.AddDays((double) j);
                    
                    HistoryItem historyItem = new HistoryItem();
                    historyItem._historyMeetingName ="Project Meeting " + j;
                    historyItem._historyProjectGroup = "Group " + i;
                    historyItem._historyModule = "Module";
                    historyItem._historyMeetingDate = date;

                    testList.Add(historyItem);
                }
            }
            return testList;
        }

        private List<NotificationItem> CreateNotificationsTestList()
        {
            List<NotificationItem> testList = new List<NotificationItem>();

            for (int i = 0; i < 5; i++)
            {

                for (int j = 0; j < 3; j++)
                {
                    DateTime date = DateTime.Now.AddDays((double)j);

                    NotificationItem notificationItem = new NotificationItem();
                    notificationItem._notificationMeetingName = "Meeting " + j;
                    notificationItem._notificationProjectGroup = "Group " + i;
                    notificationItem._notificationModule = "Module";
                    notificationItem._notificationDescription = "Was Updated by Duy";
                    notificationItem._notificationDate = date;

                    testList.Add(notificationItem);
                }
            }
            return testList;
        }

//event handlers---------------------------------------------------------------------------------------------

        public void MeetingItem_Click(object sender, RoutedEventArgs e)
        {
            var toSend = App.Current as App;
            TextBlock senderobj = (TextBlock) e.OriginalSource;
            toSend._meetingSelected = senderobj.Text; ;
            NavigationService.Navigate(new Uri("/EditMeetingForm.xaml", UriKind.Relative));
        }

        private void LoginToIVLEButton_Click(object sender, EventArgs e)
        {
            // navigate
            this.NavigationService.Navigate(new Uri("/IVLElogin.xaml", UriKind.Relative));
        }

        private void LandingPage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (((Pivot)sender).SelectedIndex)
            {
                case 0:
                    ApplicationBar.IsVisible = true;
                    break;

                case 1:
                    ApplicationBar.IsVisible = false;
                    break;

                case 2:
                    ApplicationBar.IsVisible = false;
                    break;
            }
        }

        private void CreateMeetingButton_Click(object sender, EventArgs e)
        {
            if (userID == "UserID.txt does not exist" || userID == "")
                this.NavigationService.Navigate(new Uri("/IVLElogin.xaml", UriKind.Relative));
            else
                this.NavigationService.Navigate(new Uri("/GroupSelection.xaml", UriKind.Relative));
        }

    }
}